package com.jz.community.moduleshoppingguide.search.ui;

import android.annotation.SuppressLint;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.commview.commPagerAdapter.CommonViewPagerAdapter;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.search.utils.SearchHistorySpUtils;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by Tony.Fan on 2018/6/4 09:27
 */
public class SearchListActivity extends BaseMvpActivity {
    @BindView(R2.id.search_result_delete)
    ImageView searchResultDelete;
    @BindView(R2.id.search_result_edit)
    EditText searchResultEdit;
    @BindView(R2.id.search_result_rl)
    RelativeLayout searchResultRl;
    @BindView(R2.id.search_result_btn)
    TextView searchResultBtn;
    @BindView(R2.id.search_result_toolbar)
    Toolbar searchResultToolbar;
    @BindView(R2.id.search_result_tab)
    SlidingTabLayout searchResultTab;
    @BindView(R2.id.search_result_viewpager)
    ViewPager searchResultViewpager;
    private String[] titles = {"社区人商品", "楼下小店"};
    private String keyWord;
    private int searchFromType;

    private GoodsListFragment goodsListFragment;
    private ShopNearFragment shopNearFragment;

    @Override
    protected int getContentView() {
        return R.layout.module_shoppingguide_activity_search_new_result;
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(searchResultToolbar);
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        keyWord = getIntent().getStringExtra("keyWord");
        searchFromType = getIntent().getIntExtra("isSearchFrom", 1);
        searchResultEdit.setText(keyWord);
        searchResultEdit.setSelection(keyWord.length());
        searchTextChangeEvents();
        initViewPager();
    }

    @SuppressLint("CheckResult")
    private void searchTextChangeEvents() {
        RxTextView.textChangeEvents(searchResultEdit)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(onTextChangeEvent -> {
                    if (!Preconditions.isNullOrEmpty(onTextChangeEvent.text().toString())) {
                        SHelper.vis(searchResultDelete);
                        if (keyWord.equals("充话费") || keyWord.equals("话费") || keyWord.equals("手机充值")) {
                            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.RECHARGE_PHONE);
                        } else {
                            //给两个Fragment传值，重新请求数据
                            if (!keyWord.equals(onTextChangeEvent.text().toString())) {
                                keyWord = onTextChangeEvent.text().toString();
                                SearchHistorySpUtils.getInstance().saveSearchHotWord(SearchListActivity.this, keyWord);
                                searchTypeGoods(searchFromType, true);
                            }
                        }
                    } else {
                        SHelper.gone(searchResultDelete);
                    }
                });
    }

    @Override
    protected void addListener() {
        super.addListener();
        searchResultEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                keyWord = searchResultEdit.getText().toString().trim();
                String hint = searchResultEdit.getHint().toString().trim();
                if (!Preconditions.isNullOrEmpty(keyWord)) {
                    if (keyWord.equals("充话费") || keyWord.equals("话费") || keyWord.equals("手机充值")) {
                        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.RECHARGE_PHONE);
                    } else {
                        //给两个Fragment传值，重新请求数据
                        SearchHistorySpUtils.getInstance().saveSearchHotWord(SearchListActivity.this, keyWord);
                        searchTypeGoods(searchFromType, true);
                    }
                } else if (!Preconditions.isNullOrEmpty(hint)) {
                    if (hint.equals("充话费") || hint.equals("话费") || hint.equals("手机充值")) {
                        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.RECHARGE_PHONE);
                    } else {
                        //给两个Fragment传值，重新请求数据
                        SearchHistorySpUtils.getInstance().saveSearchHotWord(SearchListActivity.this, keyWord);
                        searchTypeGoods(searchFromType, true);
                    }
                } else {
                    showNormal("请输入搜索关键字");
                }
            }
            return false;
        });
        searchResultBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        searchResultDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchResultEdit.setText("");
                finish();
            }
        });
    }

    private void initViewPager() {

        CommonViewPagerAdapter viewPagerAdapter = new CommonViewPagerAdapter(getSupportFragmentManager());

        goodsListFragment = new GoodsListFragment();

        shopNearFragment = new ShopNearFragment();

        goodsListFragment.setKeyWord(keyWord);

        shopNearFragment.setKeyWord(keyWord);
        // 社区人商品
        viewPagerAdapter.addFragment(goodsListFragment);

        // 楼下小店
        viewPagerAdapter.addFragment(shopNearFragment);

        searchResultViewpager.setAdapter(viewPagerAdapter);
        searchResultTab.setViewPager(searchResultViewpager, titles);

        searchTypeGoods(searchFromType, false);

        searchResultViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    searchFromType = 1;
                } else {
                    searchFromType = 2;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    /**
     * 搜索不同类型商品
     *
     * @param searchFromType
     */
    private void searchTypeGoods(int searchFromType, boolean isChangeItem) {
        switch (searchFromType) {
            case 1:
                if (goodsListFragment != null) {
                    if (isChangeItem) {
                        goodsListFragment.changeSearch(keyWord);
                    }
                    searchResultViewpager.setCurrentItem(0);
                }
                break;
            case 2:
                if (shopNearFragment != null) {
                    if (isChangeItem) {
                        shopNearFragment.changeSearch(keyWord);
                    }
                    searchResultViewpager.setCurrentItem(1);
                }
                break;
        }
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

}
